package com.ljm.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ljm.controller.utils.R;
import com.ljm.domain.Book;
import com.ljm.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private IBookService iBookService;

    // 增删改查
    @GetMapping
    public R getAll(){
        return new R (true,iBookService.list());
    }

    @PostMapping
    public  R save(@RequestBody Book book){
//        return new R(iBookService.save(book));
        boolean flag = iBookService.save(book);
        return new R(flag,flag? "添加成功^_^": "添加失败-_-!");
    }

    @PutMapping
    public  R update(@RequestBody Book book){
       return new R(iBookService.updateById(book));
    }

    @DeleteMapping("{id}")
    public R delete(@PathVariable Integer id){
        return new R(iBookService.removeById(id));
    }

    // 查单个 http://localhost/books/2
    @GetMapping("{id}")
    public R getById(@PathVariable Integer id){
        return new R(true,iBookService.getById(id));
    }

    // 分页查询
    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage,@PathVariable int pageSize,Book book){
        IPage<Book> page = iBookService.getPage(currentPage,pageSize,book);
        // 如果当前的页码值大于总页码值，那么重新执行查询操作，使用最大页码值作为当前的页码值
        if(currentPage>page.getPages()){
            page = iBookService.getPage((int)page.getPages(),pageSize,book);
        }
        return new R(true,page);
    }
}






















